package com.glasgowcompsoc.musicplayer.player;

import java.util.ArrayList;
import java.util.List;

/**
 * This class offers simple playlist management
 * functionality. The playlist manager is a singleton;
 * get instance with the getPlaylistManager() method.
 */
public class PlaylistManager {
	private static PlaylistManager instance;
	private List<Song> currentPlaylist;
	private int playlistIndex;
	
	private PlaylistManager() {
		newPlaylist();
	}
	
	public static PlaylistManager getPlaylistManager() {
		if (instance == null) {
			instance = new PlaylistManager();
		}
		
		return instance;
	}
	
	public List<Song> getCurrentPlaylist() {
		return currentPlaylist;
	}
	
	public void newPlaylist() {
		currentPlaylist = new ArrayList<Song>();
	}
	
	public void addSong(Song song) {
		currentPlaylist.add(song);
	}
	
	public void removeSong(Song song) {
		currentPlaylist.remove(song);
	}
	
	public void savePlaylist() {
		
	}
	
	public Song currentSong() {
		if (currentPlaylist.isEmpty())
			return null;
		
		return currentPlaylist.get(playlistIndex);
	}
	
	public Song nextSong() {
		if (currentPlaylist.isEmpty())
			return null;
		
		playlistIndex = (playlistIndex + 1) % currentPlaylist.size();
		
		return currentSong();
	}
	
	public Song previousSong() {
		if (currentPlaylist.isEmpty())
			return null;
		
		/* Note: Can't use modulo arithmetic here, Java calculates
		 * it incorrectly for negative values...
		 */
		
		if (playlistIndex == 0)
			playlistIndex = currentPlaylist.size() - 1;
		else
			playlistIndex--;
		
		return currentSong();
	}
	
	public Song getSongAt(int i) {
		if (i >= currentPlaylist.size()) {
			return null;
		} else {
			playlistIndex = i;
			
			return currentSong();
		}
	}
	
	public boolean isEndOfPlaylist() {
		return playlistIndex == currentPlaylist.size() - 1;
	}
	
	public int nextSongIndex() {
		return (playlistIndex + 1) % currentPlaylist.size();
	}
	
	public int previousSongIndex() {
		if (playlistIndex == 0)
			return currentPlaylist.size() - 1;
		else
			return playlistIndex - 1;
	}
}
